package com.helmlabs.grouper.forms.model.actions;

import java.util.ArrayList;
import java.util.List;

import com.helmlabs.grouper.forms.model.Form;
import com.helmlabs.grouper.forms.model.field.AbstractField;
import com.helmlabs.grouper.forms.model.validator.FieldValidator;

public class ValidateFormAction extends AbstractFormAction {
	
	public Form execute(Form form){
		// make sure there are fields in the form
		if (form.getFields()!=null ){
			
			// iterate over each field
			for (AbstractField field : form.getFields()){
				
				// list holding all the error messages
				List<String> errorMessage = new ArrayList(); 
				
				// iterator over each field validator
				for (FieldValidator validator : field.getValidators()){
					
					if (!validator.isValid(field)){
						errorMessage.add(validator.getMessage());
					}
				}
				
				if (errorMessage.size()>0){
					field.setHasErrors(true);
					form.setErrorsExist(true);
				}
			}
		}
		return form;
	}

}
